<template>
  <div class="container" style="margin-top: 50px; margin-bottom: 50px;">
    <el-card shadow="always" style="min-height: 500px;">
      <el-container>
        <el-aside>
          <MemberMenu/>
        </el-aside>
        <el-main>
          <el-row>
            <el-col :span="24">
              <el-card class="box-card" shadow="hover">
                <div slot="header" class="clearfix">
                  <span style="color: #409EFF;">
                    <i class="el-icon-warning-outline"></i>
                    已保存了{{ addressList.length }}条地址信息，还能添加{{ 10 - addressList.length }}条地址信息
                  </span>
                  <el-button class="float-right" type="primary" @click="handlerDialog" size="small">新增</el-button>
                </div>
                <el-table
                    v-if="addressList.length > 0"
                    :data="addressList"
                    style="width: 100%">
                  <el-table-column
                      align="center"
                      prop="name"
                      label="联系人"
                      width="70">
                  </el-table-column>
                  <el-table-column
                      align="center"
                      prop="telephoneNumber"
                      label="手机号码"
                      width="110">
                  </el-table-column>
                  <el-table-column
                      align="center"
                      prop="detail"
                      label="详细地址">
                  </el-table-column>
                  <el-table-column
                      align="center"
                      label="标签"
                      width="80">
                    <template slot-scope="scope">
                      <el-button type="primary" plain disabled size="small">{{ scope.row.tags }}</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                      align="center"
                      label="操作"
                      width="100">
                    <template slot-scope="scope">
                      <el-button type="danger" size="small" @click="deleteAddress(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                      align="center"
                      label=""
                      width="100">
                    <template slot-scope="scope">
                      <el-link class="text-info" style="cursor: pointer" @click="setDefaultAddress(scope.row)"
                              v-if="scope.row.adefault==0">设为默认
                      </el-link>
                      <el-button size="small" type="danger" plain disabled v-else>默认地址</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-empty :image-size="200" v-else></el-empty>
              </el-card>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </el-card>

    <!-- 地址表单 -->
    <el-dialog title="地址信息" :visible.sync="dialogFormVisible" :width="'30%'">
      <el-row style="padding: 50px;">
        <el-col :span="24">
          <el-form
              ref="addressForm"
              :model="addressForm"
              :rules="addressRules"
              label-width="100px">
            <el-form-item prop="name" label="收货人">
              <el-input
                  v-model="addressForm.name"
                  clearable
                  type="text"
                  placeholder="收货人">
              </el-input>
            </el-form-item>

            <el-form-item prop="telephoneNumber" label="手机号">
              <el-input
                  v-model="addressForm.telephoneNumber"
                  clearable
                  type="text"
                  placeholder="手机号">
              </el-input>
            </el-form-item>

            <el-form-item prop="tags" label="标签">
              <el-select
                  v-model="addressForm.tags"
                  filterable
                  allow-create
                  default-first-option
                  placeholder="请选择标签">
                <el-option
                    v-for="item in tagOptions"
                    :key="item"
                    :label="item"
                    :value="item">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="省市区" prop="province">
              <el-row type="flex" :gutter="20">
                <el-col :span="8">
                  <el-select ref="province" @change="handlerGetCity()" v-model="addressForm.province" placeholder="—— 省份 ——">
                    <el-option v-for="province in provinceList" :key="province.provinceId" :label="province.provinceName"
                               :value="province.provinceId"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <el-select ref="city" @change="handlerGetDistrict" v-model="addressForm.city" placeholder="—— 城市 ——">
                    <el-option v-for="city in cityList" :key="city.cityId" :label="city.cityName"
                               :value="city.cityId"></el-option>
                  </el-select>
                </el-col>
                <el-col :span="8">
                  <el-select ref="area" v-model="addressForm.area" placeholder="—— 区/县 ——">
                    <el-option v-for="district in districtList" :key="district.districtId" :label="district.districtName"
                               :value="district.districtId"></el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item prop="detail" label="详细地址">
              <el-input
                  v-model="addressForm.detail"
                  clearable
                  type="text"
                  placeholder="详细地址">
              </el-input>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addAddress('addressForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getAddressList, addAddress, setDefaultAddress, deleteAddress} from "@/api/member/member";
import {getProvince, getCityByProvinceId, getDistrictByCityId} from "@/api/Region/region";
import MemberMenu from "@/views/components/MemberMenu";

export default {
  name: 'memberAddress',
  components: {MemberMenu},
  data() {
    return {
      tagOptions: ['家', '公司', '学校'],
      addressList: [],
      provinceList: [],
      cityList: [],
      districtList: [],
      loading: false,
      dialogFormVisible: false,
      addressForm: {
        name: "",
        province: "",
        city: "",
        area: "",
        detail: "",
        telephoneNumber: "",
        tags: "",
        adefault: 0,
      },
      addressRules: {
        name: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入收货人姓名",
          },
        ],
        province: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择省份",
          },
        ],
        city: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择城市",
          },
        ],
        area: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请选择区/县",
          },
        ],
        detail: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入详细地址",
          },
        ],
        tags: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入标签",
          },
        ],
        telephoneNumber: [
          {
            required: true,
            trigger: ["blur", "change"],
            message: "请输入手机号",
          },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: "请输入正确的号码格式",
            trigger: ["blur", "change"],
          },
        ],
      }
    }
  },
  computed: {},
  mounted() {
    this.getAddressList()
    this.handlerGetProvince()
  },
  methods: {
    handlerGetProvince() {
      getProvince().then((res) => {
        this.provinceList = res.data;
      })
    },
    handlerGetCity() {
      this.addressForm.city = null;
      this.addressForm.area = null;
      this.cityList = [];
      this.districtList = [];
      const provinceId = this.addressForm.province;
      getCityByProvinceId(provinceId).then((res) => {
        this.cityList = res.data;
      })
    },
    handlerGetDistrict() {
      this.addressForm.area = null;
      this.districtList = [];
      const cityId = this.addressForm.city;
      getDistrictByCityId(cityId).then((res) => {
        this.districtList = res.data;
      })
    },
    idNumberFormatter(val) {
      return val.substring(0, 3) + '***********' + val.substring(14)
    },
    // 获取地址列表
    getAddressList() {
      getAddressList().then((res) => {
        this.addressList = res.data;
      })
    },
    // 新增地址信息
    addAddress(formName) {
      if (this.addressList.length >= 10) {
        this.$message({
          message: "地址信息已达上限",
          type: 'warning'
        })
      } else {
        this.$refs[formName].validate((vaild) => {
          if (vaild) {
            this.loading = true,
                addAddress(this.addressForm).then((res) => {
                  this.$message({
                    message: res.msg,
                    type: 'warning'
                  }),
                      this.getAddressList()
                  this.dialogFormVisible = false
                }).finally(() => {
                  this.loading = false
                });
          }
        })
      }
    },
    deleteAddress(row) {
      const dataId = row.dataId;
      this.$confirm('是否确认该条地址信息').then(function () {
        return deleteAddress(dataId);
      }).then(() => {
        this.getAddressList();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      })
    },
    setDefaultAddress(row) {
      setDefaultAddress(row).then(() => {
        this.$message({
          type: 'success',
          message: '默认地址更换成功'
        });
        this.getAddressList()
      })
    },
    handlerDialog() {
      this.reset()
      this.dialogFormVisible = true
    },
    // 表单重置
    reset() {
      this.addressForm = {
          name: null,
          province: null,
          city: null,
          area: null,
          detail: null,
          telephoneNumber: null,
          tags: null,
          adefault: 0,
      }
    },
  },
};
</script>

<style lang="scss" scoped>

</style>
